//
//  QBMFImagePrviewViewController.m
//  QBImagePickerControllerDemo
//
//  Created by Michael Fan on 14/11/13.
//  Copyright (c) 2014年 Katsuma Tanaka. All rights reserved.
//

#import "QBMFImagePrviewViewController.h"
#import "QBAssetsCollectionViewController.h"
#import <ImageIO/ImageIO.h>

#define QBMF_PADDING                  10

@interface QBMFImagePrviewViewController ()
{
    UIScrollView *_pagingScrollView;
    UIToolbar *previewToolBar;
    UIBarButtonItem *selectedItem;
    UIButton *btnSelected;
    
    BOOL bSelected[20];
    int maxSelected;
    int nowSelected;
    
    UIBarButtonItem *doneItem;
}
@end

@implementation QBMFImagePrviewViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    selectedItem.title = [NSString stringWithFormat:NSLocalizedStringFromTable(@"selected_photos_and_maxphotos",@"QBImagePickerController", nil),nowSelected,maxSelected];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    QBMFImagePickerController *QBMFController = ((QBMFImagePickerController *)self.navigationController);
    QBAssetsCollectionViewController *assetsController = [[self.navigationController viewControllers] objectAtIndex:1];
    int deleteCount = 0;
    for (int i = 0; i < maxSelected; i++) {
        if (!bSelected[i]) {
            //删除collectionView中的选中状态
            NSURL *URL = [QBMFController.selectedAssetURLs objectAtIndex:i-deleteCount];
            for (NSInteger j = 0; j < assetsController.assets.count; j++) {
                ALAsset *asset = [assetsController.assets objectAtIndex:j];
                NSURL *assetURL = [asset valueForProperty:ALAssetPropertyAssetURL];
                if ([assetURL isEqual:URL]) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:0];
                    [assetsController.collectionView deselectItemAtIndexPath:indexPath animated:NO];
                }
            }
            
            [QBMFController.selectedAssetURLs removeObjectAtIndex:i-deleteCount];
            deleteCount++;
        }
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor blackColor];
    self.edgesForExtendedLayout = UIRectEdgeTop;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
        self.wantsFullScreenLayout = YES;
    }

    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]){
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.view.clipsToBounds = YES;
    
    maxSelected = (int)[((QBMFImagePickerController *)self.navigationController).selectedAssetURLs count];
    nowSelected = maxSelected;
    self.title = [NSString stringWithFormat:@"%d/%d",1,maxSelected];
    // Setup paging scrolling view
    CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
    _pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame];
    _pagingScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _pagingScrollView.pagingEnabled = YES;
    _pagingScrollView.delegate = self;
    _pagingScrollView.showsHorizontalScrollIndicator = NO;
    _pagingScrollView.showsVerticalScrollIndicator = NO;
    _pagingScrollView.backgroundColor = [UIColor blackColor];
    _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
    [self.view addSubview:_pagingScrollView];
    
    previewToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-44+self.view.frame.origin.y, self.view.frame.size.width, 44)];
    [self.view addSubview:previewToolBar];
    NSMutableArray *items = [[NSMutableArray alloc] init];
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [items addObject:flexSpace];
    flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [items addObject:flexSpace];
    selectedItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    [items addObject:selectedItem];
    flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [items addObject:flexSpace];
    doneItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedStringFromTable(@"done", @"QBImagePickerController", nil) style:UIBarButtonItemStyleDone target:self action:@selector(toolBarDone)];
    [items addObject:doneItem];
    [previewToolBar setItems:items];
    
    btnSelected = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnSelected setImage:[UIImage imageNamed:@"ImageSelectedOn.png"] forState:UIControlStateNormal];
    [btnSelected setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    btnSelected.frame = CGRectMake(0, 0, 60, 44);
    btnSelected.backgroundColor = [UIColor clearColor];
    [btnSelected addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithCustomView:btnSelected];
    [self.navigationItem setRightBarButtonItem:cancelButton animated:NO];
    
    self.selectedAssets = [NSMutableArray array];
    __block QBMFImagePickerController *QBMFController = ((QBMFImagePickerController *)self.navigationController);
    for (NSURL *selectedAssetURL in QBMFController.selectedAssetURLs) {
        [QBMFController.assetsLibrary assetForURL:selectedAssetURL
                                      resultBlock:^(ALAsset *asset) {
                                          // Add asset
                                          ALAssetRepresentation *rep = [asset defaultRepresentation];
                                          [self.selectedAssets addObject:[UIImage imageWithCGImage:[rep fullScreenImage]]];
                                          if ([QBMFController.selectedAssetURLs count] == [self.selectedAssets count]) {
                                              [self tilePages];
                                          }
                                      } failureBlock:^(NSError *error) {
                                          
                                      }];
    }
    
    //初始化时全为选中状态
    for (int i = 0; i < maxSelected; i++) {
        bSelected[i] = YES;
    }
}

-(void)toolBarDone
{
    int deleteCount = 0;
    for (int i = 0; i < [self.selectedAssets count]; i++) {
        if (!bSelected[i]) {
            [self.selectedAssets removeObjectAtIndex:i-deleteCount];
            deleteCount++;
        }
    }
    
    QBMFImagePickerController *QBMFController = ((QBMFImagePickerController *)self.navigationController);
    [QBMFController imagePickerFinish:self.selectedAssets];
}

-(void)selectAction:(id)sender
{
    int selecetIndex = (_pagingScrollView.contentOffset.x+_pagingScrollView.bounds.size.width/2.0f)/_pagingScrollView.bounds.size.width;
    bSelected[selecetIndex] = !bSelected[selecetIndex];
    [btnSelected setImage:[UIImage imageNamed:(bSelected[selecetIndex])?@"ImageSelectedOn.png":@"ImageSelectedOff.png"] forState:UIControlStateNormal];
    if (bSelected[selecetIndex]) {
        nowSelected++;
    }
    else
        nowSelected--;
    
    selectedItem.title = [NSString stringWithFormat:NSLocalizedStringFromTable(@"selected_photos_and_maxphotos",@"QBImagePickerController", nil),nowSelected,maxSelected];
    
    doneItem.enabled = (nowSelected>0);
    
}

- (void)tilePages {
    
    for (int i = 0; i < [self.selectedAssets count]; i++) {
        QBMFZoomingScrollView *page = [[QBMFZoomingScrollView alloc] initWithQBMFImagePrviewViewController:self];
        page.frame = [self frameForPageAtIndex:i];
        page.photo = [self.selectedAssets objectAtIndex:i];
        [_pagingScrollView addSubview:page];
    }
    
}

- (CGRect)frameForPageAtIndex:(NSUInteger)index {
    CGRect bounds = _pagingScrollView.bounds;
    CGRect pageFrame = bounds;
    pageFrame.size.width -= (2 * QBMF_PADDING);
    pageFrame.origin.x = (bounds.size.width * index) + QBMF_PADDING;
    return CGRectIntegral(pageFrame);
}

- (CGRect)frameForPagingScrollView {
    CGRect frame = self.view.bounds;
    frame.origin.x -= QBMF_PADDING;
    frame.size.width += (2 * QBMF_PADDING);
    return CGRectIntegral(frame);
}
- (CGSize)contentSizeForPagingScrollView
{
    CGRect bounds = _pagingScrollView.bounds;
    return CGSizeMake(bounds.size.width * [((QBMFImagePickerController *)self.navigationController).selectedAssetURLs count], bounds.size.height);
}

-(void)tapPhotoEventAction
{
    [UIApplication sharedApplication].statusBarHidden = ![UIApplication sharedApplication].statusBarHidden;
    self.navigationController.navigationBarHidden = !self.navigationController.navigationBarHidden;
    previewToolBar.hidden = !previewToolBar.hidden;

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int selecetIndex = (_pagingScrollView.contentOffset.x+_pagingScrollView.bounds.size.width/2.0f)/_pagingScrollView.bounds.size.width;
    if (selecetIndex < 0 || selecetIndex == maxSelected) {
        return;
    }
    [btnSelected setImage:[UIImage imageNamed:(bSelected[selecetIndex])?@"ImageSelectedOn.png":@"ImageSelectedOff.png"] forState:UIControlStateNormal];
    self.title = [NSString stringWithFormat:@"%d/%d",selecetIndex+1,maxSelected];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
